import mitt from 'mitt'

export class WebSocketWrapper {

  constructor(url = 'ws://server1.czdata.top:38001/', clientId = 'user1') {
    this.ws = null
    this.url = url
    this.clientId = clientId
    this.connectingLock = false
    this.reconnectTimer = null
    this.emitter = mitt()
  }

  // 如需要保证连接稳定，还需要加心跳处理
  init() {
    let ws
    if (WebSocket) {
      ws = new WebSocket(this.url + this.clientId)
    } else {
      console.log("您的浏览器不支持 WebSocket!")
      return
    }

    ws.onmessage = (ev) => {
      console.log("websocket onmessage:", ev)
      this.emitter.emit('ws-message', ev.data)
    }

    ws.onclose = (ev) => {
      console.log("websocket onclose", ev)
    }

    ws.onopen = (ev) => {
      console.log("websocket onopen", ev)
    }

    ws.onerror = (ev) => {
      console.log("websocket onerror", ev)
      setTimeout(() => {
        this.init()
      }, 1000)
    }

    this.ws = ws
    return this
  }

  send(data) {
    let msg = data instanceof Object ? JSON.stringify(data) : data
    this.ws.send(msg)
    console.log("websocket send:", msg)
  }

  getStatus() {
    if (ws.readyState == 0) {
      return "Unconnected"
    } else if (ws.readyState == 1) {
      return "Connected"
    } else if (ws.readyState == 2) {
      return "Closing"
    } else if (ws.readyState == 3) {
      return "Closed"
    }
  }

  getEmitter() {
    return this.emitter
  }
}

export default new WebSocketWrapper().init()
